package com.ruoyi.safe.controller.api;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.CommonCheckType;
import com.ruoyi.common.core.domain.entity.ListType;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.vo.ListItemVo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.safe.domain.*;
import com.ruoyi.safe.domain.dto.UserSearchDTO;
import com.ruoyi.safe.domain.vo.BizDutyRegionVO;
import com.ruoyi.safe.domain.vo.ListRequestVo;
import com.ruoyi.safe.service.*;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 手机端-清单列表接口
 *
 * @Auther: lihongming
 * @Date: 2023-11-10 13:41
 * @Description: com.ruoyi.safe.controller.api
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/list")
public class ListController {
    @Autowired
    private IListTypeService listTypeService;
    @Autowired
    private IListDeviseService listDeviseService;
    @Autowired
    private IBizDutyRegionService bizDutyRegionService;
    @Autowired
    private ICommonProjectService commonProjectService;
    @Autowired
    private ICommonUserService commonUserService;
    @Autowired
    private ICommonCheckTypeService commonCheckTypeService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private IBizSafeAttachService bizSafeAttachService;
    @Autowired
    private ICommonCooperatorService commonCooperatorService;
    @Autowired
    private IListConstructionService listConstructionService;
    @Autowired
    private IListMaintenanceService listMaintenanceService;
    @Autowired
    private IListManageService listManageService;

    /**
     * 获取清单分类下拉树列表
     */
    @PostMapping("/treeselect")
    public AjaxResult treeselect(@RequestBody ListType listType) {
        // 设计清单
        List<ListDevise> listDevises = listDeviseService.selectListDeviseListAll(ListDevise.builder().status("0").build());
        // 施工清单
        List<ListConstruction> listConstructions = listConstructionService.selectListConstructionListAll(ListConstruction.builder().status("0").build());
        // 养护清单
        List<ListMaintenance> listMaintenances = listMaintenanceService.selectListMaintenanceListAll(ListMaintenance.builder().status("0").build());
        // 管理清单
        List<ListManage> listManages = listManageService.selectListManageListAll(ListManage.builder().status("0").build());
        // 清单分类
        listType.setStatus("0");
        List<ListType> archivesTypes = listTypeService.selectListTypeList(listType);
        for (int i = 0; i < archivesTypes.size(); i++) {
            if (archivesTypes.get(i).getTypeNo().startsWith("1")) {
                int index = i;
                List<ListDevise> collect = listDevises.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListDevise listDevise : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listDevise, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("2")) {
                int index = i;
                List<ListConstruction> collect = listConstructions.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListConstruction listConstruction : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listConstruction, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("3")) {
                int index = i;
                List<ListMaintenance> collect = listMaintenances.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListMaintenance listMaintenance : collect) {
                    ListItemVo build = ListItemVo.builder().build();
                    BeanUtils.copyProperties(listMaintenance, build);
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            } else if (archivesTypes.get(i).getTypeNo().startsWith("4")) {
                int index = i;
                List<ListManage> collect = listManages.stream().filter(c -> archivesTypes.get(index).getId().toString().equals(c.getTypeNo())).collect(Collectors.toList());
                List<ListItemVo> listItemVos = new ArrayList<>();
                for (ListManage listManage : collect) {
                    ListItemVo build = ListItemVo.builder()
                            .typeNo(listManage.getTypeNo())
                            .id(listManage.getId())
                            .riskLevel(listManage.getRiskLevel())
                            .dangerLevel(listManage.getDangerLevel())
                            .riskFactor(listManage.getManageBehaviors())
                            .controlMeasure(listManage.getControlMeasure())
                            .normativeBasis(listManage.getNormativeBasis())
                            .build();
                    listItemVos.add(build);
                }
                archivesTypes.get(i).setListItemVos(listItemVos);
            }
        }
        List<TreeSelect> treeSelects = listTypeService.buildTypeTreeSelect(archivesTypes);
        return AjaxResult.success(treeSelects);
    }


    /**
     * 获取责任区域树
     *
     * @param bizDutyRegion
     * @return
     */
    @PostMapping("/region/tree")
    public AjaxResult getRegionList(@RequestBody BizDutyRegion bizDutyRegion) {
        List<BizDutyRegionVO> bizDutyRegionVOS = bizDutyRegionService.selectBizDutyRegionListVO(bizDutyRegion);
        List<TreeNode<String>> nodeList = bizDutyRegionVOS.stream()
                .map(bizDutyRegionVO -> {
                    TreeNode<String> treeNode = new TreeNode<>();
                    treeNode.setId(String.valueOf(bizDutyRegionVO.getId()));
                    treeNode.setParentId(String.valueOf(bizDutyRegionVO.getParentId()));
                    treeNode.setName(bizDutyRegionVO.getRegionName());
                    treeNode.setWeight(bizDutyRegionVO.getSort());
                    Map<String, Object> map = new HashMap<>();
                    map.put("correctorUserId", bizDutyRegionVO.getCorrectorUserId());
                    map.put("correctorUserName", bizDutyRegionVO.getCorrectorUserName());
                    map.put("notifierUserId", bizDutyRegionVO.getNotifierUserId());
                    map.put("notifierUserName", bizDutyRegionVO.getNotifierUserName());
                    map.put("reviewerUserId", bizDutyRegionVO.getReviewerUserId());
                    map.put("reviewerUserName", bizDutyRegionVO.getReviewerUserName());
                    treeNode.setExtra(map);
                    return treeNode;
                })
                .collect(Collectors.toList());
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0");

        return AjaxResult.success(treeNodes);
    }

    /**
     * 获取项目列表
     */
    @PostMapping("/in/project")
    public AjaxResult selInProjectList(@RequestBody ListRequestVo listRequestVo) {
        return AjaxResult.success(commonProjectService.selInProjectList(listRequestVo.getUserName()));
    }

    /**
     * 检查类型树
     *
     * @param commonCheckType
     * @return
     */
    @PostMapping("/checkType")
    public AjaxResult checkType(@RequestBody CommonCheckType commonCheckType) {
        commonCheckType.setStatus("0");
        List<CommonCheckType> commonCheckTypes = commonCheckTypeService.selectCommonCheckTypeList(commonCheckType);
        List<TreeNode<String>> nodeList = commonCheckTypes.stream()
                .map(checkType -> {
                    TreeNode<String> treeNode = new TreeNode<>();
                    treeNode.setId(String.valueOf(checkType.getId()));
                    treeNode.setParentId(String.valueOf(checkType.getParentId()));
                    treeNode.setName(checkType.getCheckTypeName());
                    treeNode.setWeight(checkType.getOrderNum());
                    return treeNode;
                })
                .collect(Collectors.toList());
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "0");
        return AjaxResult.success(treeNodes);
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @PostMapping(value = "/dictType")
    public AjaxResult dictType(@RequestBody ListRequestVo listRequestVo) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(listRequestVo.getDictType());
        if (StringUtils.isNull(data)) {
            data = new ArrayList<SysDictData>();
        }
        return AjaxResult.success(data);
    }

    /**
     * 获取项目管理详细信息
     */
    @PostMapping(value = "/project")
    public AjaxResult getInfo(@RequestBody ListRequestVo listRequestVo) {
        return AjaxResult.success(commonProjectService.selectCommonProjectById(listRequestVo.getProjectId()));
    }

    /**
     * 获取安全相册
     */
    @PostMapping(value = "/album")
    public AjaxResult getAlbum(@RequestBody ListRequestVo listRequestVo) {
        BizSafeAttach bizSafeAttach = BizSafeAttach.builder()
                .projectId(listRequestVo.getProjectId())
                .build();
        bizSafeAttach.setCreateBy(listRequestVo.getUserName());
        return AjaxResult.success(bizSafeAttachService.selectBizSafeAttachListAlbum(bizSafeAttach));
    }

    /**
     * 获取分包单位
     */
    @PostMapping(value = "/subpackage")
    public AjaxResult getSubpackage(@RequestBody ListRequestVo listRequestVo) {
        List<CommonCooperator> commonCooperators = commonCooperatorService.selectSubPackageList(new CommonCooperator());
        //筛选出分包单位 - 3 , 劳务分包 -4
        List<CommonCooperator> subpackage = commonCooperators.stream().filter(commonCooperator1 -> commonCooperator1.getEnterpriseType().equals("3")).collect(Collectors.toList());
        List<CommonCooperator> laborSubpackage = commonCooperators.stream().filter(commonCooperator1 -> commonCooperator1.getEnterpriseType().equals("4")).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("subpackage", subpackage);
        map.put("laborSubpackage", laborSubpackage);
        return AjaxResult.success(map);
    }

    /**
     * 获取项目以分配的人员
     */
    @PostMapping(value = "/projectUser")
    public AjaxResult getProjectUser(@RequestBody ListRequestVo listRequestVo) {
        UserSearchDTO userSearchDTO = new UserSearchDTO();
        userSearchDTO.setProjectId(listRequestVo.getProjectId());
        return AjaxResult.success(commonUserService.selectCommonUserList(userSearchDTO));
    }

    /**
     * 获取检查类型
     */
    @PostMapping(value = "/checkTypeList")
    public AjaxResult getCheckTypeList(@RequestBody ListRequestVo listRequestVo) {
        return AjaxResult.success(commonCheckTypeService.selectCommonCheckTypeListByParentId());
    }

    /**
     * 根据区域id  获取：通知人、整改人、复查人
     */
    @PostMapping(value = "/regionUser")
    public AjaxResult getRegionUser(@RequestBody ListRequestVo listRequestVo) {
        return AjaxResult.success(bizDutyRegionService.selectBizDutyRegionByIdAndProjectId(listRequestVo));
    }

    /**
     * 查询所有上级部门的人员列表
     */
    @PostMapping(value = "/higherAuthoritiesUsers")
    public AjaxResult higherAuthoritiesUsers(@RequestBody ListRequestVo listRequestVo) {
        return AjaxResult.success(bizDutyRegionService.higherAuthoritiesUsers(listRequestVo));
    }

}
